<script setup lang="ts">
import { initiateAfterSalesAPI } from '@/apis/initiateAfterSales'
import { uploadImageAPI } from '@/apis/uploadImage'
import { useUserInfoStore } from '@/store/userInfo'

// Assets
import modalSuccessIcon from '@/static/images/modal/success.png'
import { endAfterSalesAPI } from '@/apis/endAfterSales'

const router = useRouter()
const userInfoStore = useUserInfoStore()

const afterId = ref('')

// 表单组件 ref
const formRef = ref<any>(null)
// loading 状态
const loading = ref(false)
// 是否显示表单提交成功弹窗
const isShowSuccessModal = ref(false)

onLoad((options) => {
  if (options && options.after_id)
    afterId.value = options.after_id
  else
    uni.showToast({ title: '获取数据失败', icon: 'none' })
})

const formData = ref({
  desc: '',
  images: [] as string[],
})

const rules = {
  desc: [
    { required: true, message: '信息不可为空' },
  ],
}

/* ---------------------------- ChooseImage START --------------------------- */
function handlePickImage() {
  uni.showActionSheet({
    itemList: ['拍摄', '从手机相册中选择'],
    success: (result) => {
      const sourceType = result.tapIndex === 0 ? 'camera' : 'album'
      uni.chooseMedia({
        count: 9,
        mediaType: ['image'],
        sourceType: [sourceType],
        sizeType: ['compressed'],
        success: (result) => {
          if (result.tempFiles.length > 0) {
            // 遍历照片临时路径的数组，将照片上传至服务器，将返回的 url 存入 formData
            result.tempFiles.forEach(async (path) => {
              const res = await uploadImageAPI(path.tempFilePath, userInfoStore.userInfo!.token!)
              if (res.data) {
                const resData = JSON.parse(res.data)
                if (resData.code === 1)
                  formData.value.images.push(resData.data.fullurl)
                else
                  uni.showToast({ title: resData.msg, icon: 'none' })
              }
              else {
                uni.showToast({ title: '上传图片失败', icon: 'none' })
              }
            })
          }
          else {
            uni.showToast({ title: '没有获取到照片', icon: 'none' })
          }
        },
      })
    },
  })
}

function handleDeleteImage(image: string) {
  formData.value.images = formData.value.images.filter(i => i !== image)
}
/* ----------------------------- ChooseImage END ---------------------------- */

/* ------------------------------- 事件处理 START ------------------------------- */
const handleSubmit = useThrottleFn(() => {
  formRef.value.validate()
    .then(async () => {
      loading.value = true
      try {
        const res = await endAfterSalesAPI({
          after_id: afterId.value,
          desc: formData.value.desc,
          images: formData.value.images.join(','),
        }, userInfoStore.userInfo!.token!)
        loading.value = false
        if (res.data?.code === 1)
          isShowSuccessModal.value = true
        else
          uni.showToast({ title: res.data?.msg, icon: 'none' })
      }
      catch (err) {
        loading.value = false
        uni.showToast({ title: '修改失败，请重试', icon: 'none' })
      }
    })
    .catch((errors: AnyObject[]) => {
      if (errors.length > 0)
        uni.showToast({ title: errors[0].message, icon: 'none' })
    })
}, 1000)

function handleExit() {
  router.back()
}
/* -------------------------------- 事件处理 END -------------------------------- */
</script>

<template>
  <view class="min-h-screen bg-#F8F8F8">
    <Spacer height="30" />
    <uv-form ref="formRef" :model="formData" :rules="rules">
      <view class="p-30rpx bg-white rounded-10rpx">
        <uv-form-item prop="desc" :custom-style="{ padding: 0 }">
          <textarea
            v-model="formData.desc"
            class="box-border w-full min-h-200rpx text-28rpx text-#333333"
            :maxlength="-1"
            placeholder="请输入文字信息..."
            placeholder-style="color: #999999"
          />
        </uv-form-item>
        <uv-form-item prop="images" :custom-style="{ padding: 0 }">
          <PictureGrid
            mode="edit"
            :width="630"
            :cols="4"
            :pictures="formData.images"
            @pick-image="handlePickImage"
            @delete="(image) => handleDeleteImage(image)"
          />
        </uv-form-item>
      </view>
      <Spacer height="240" />
      <RGButton
        class="z-10 fixed bottom-80rpx x-center"
        @tap="handleSubmit"
      >
        提交凭证
      </RGButton>
      <Spacer height="100" />
    </uv-form>
    <uv-overlay :show="isShowSuccessModal" @tap="handleExit">
      <uv-transition mode="zoom-in" :show="isShowSuccessModal">
        <view class="relative w-screen h-screen">
          <JZTModal
            :icon="modalSuccessIcon"
            title="凭证上传成功"
            content=""
            button-label="确定"
            @confirm="handleExit"
          />
        </view>
      </uv-transition>
    </uv-overlay>
  </view>
</template>

<route lang="yaml">
name: 'uploadProof'
style:
  navigationBarTitleText: '上传凭证'
</route>
